package org.freez4.spring.configuration.metadata;

import org.freez4.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * 基于 Java 注解 Spring IoC 容器元信息配置示例。
 *
 * @author 阿坤同学
 * @date 2024/1/11 23:30
 */
// 将当前类作为 Configuration Class
@ImportResource("classpath:/META-INF/dependency-lookup-context.xml")
@Import(User.class)
@PropertySource("classpath:/META-INF/user-bean-definitions.properties") // Java 8+ @Repeatable 支持
@PropertySource("classpath:/META-INF/user-bean-definitions.properties")
// @PropertySources(@PropertySource(...))
public class AnnotatedSpringIoCContainerMetadataConfigurationDemo {

    private static final Logger logger = Logger.getLogger(AnnotatedSpringIoCContainerMetadataConfigurationDemo.class.getName());

    /**
     * user.name 是 Java Properties 默认存在，当前用户而非properties中的配置属性值。
     */
    @Bean
    public User configuredUser(@Value("${user.id}") Integer id, @Value("${user.name}") String name) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        return user;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册当前类作为 Configuration Class
        context.register(AnnotatedSpringIoCContainerMetadataConfigurationDemo.class);
        // 启动 Spring 应用上下文
        context.refresh();
        // beanName 和 bean 映射
        Map<String, User> usersMap = context.getBeansOfType(User.class);
        for (Map.Entry<String, User> entry : usersMap.entrySet()) {
            logger.log(Level.INFO, () -> "User Bean name :" + entry.getKey() + " content :" + entry.getValue());
        }
        // 关闭 Spring 应用上下文
        context.close();
    }
}